extern crate regex;
extern crate serde_json;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate clap;
mod sqlfile;
use sqlfile::BaseFile;
use std::path::Path;
use std::thread;
use std::sync::mpsc::channel;
// const D:&str = "[NONE]";

#[derive(Clap)]
#[clap(version = "1.2", author = "Qingluan")]
struct Opts {
    sql:String,
    #[clap(short = "o", long = "out", default_value = "[NONE]")]
    out:String,
    #[clap(short = "f", long = "tables", multiple = true)]
    filter_tables:Vec<String>,
    #[clap(short = "t", long = "thread", default_value = "5")]
    thread_num:usize,
}

fn main() {
    let opts = Opts::parse();
    if opts.sql != ""{
        if !Path::new(&opts.sql).exists() {
            std::process::exit(0);
        }
        let pool = threadpool::ThreadPool::new(opts.thread_num);
        let (tx,rx) = channel::<Vec<String>>();
        let out = if opts.out == "[NONE]"{
            format!("{}.OUTPUT",&opts.sql)
        }else{
            opts.out.clone()
        };
        
        
        if !Path::new(&out).exists(){
            let _ = std::fs::create_dir(&out);
        }
        thread::spawn(move || {
            sqlfile::do_in_sync_area(&out, rx);
        });
        if let Ok(pool) = opts.sql.as_str().scan_table(pool, tx.clone(),&opts.filter_tables){
            pool.join();
            tx.send(vec!["<<END>>".to_string()]).expect("closed!");
            thread::sleep(std::time::Duration::from_secs(5)); 
        }
    }
}
